package cn.xyfmzmy.builder;


/**
 * 建造者模式，通过内部类Builder来创建对象
 * 在Builder的过程中，可以加入一些逻辑判断
 */
public class User {

    // 不可变对象，通过builder创建的对象的属性值无法修改
    private final String name;
    private final Integer age;

    // 私有化构造方法，创建对象只能通过builder
    private User(Builder builder){
        this.name = builder.name;
        this.age = builder.age;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    // 让外部通过builder()方法创建Builder对象
    public static Builder builder(){
        return new Builder();
    }

    public static class Builder {

        private String name;
        private Integer age;

        // 返回Builder本身，支持链式调用
        public Builder name(String name){
            this.name = name;
            return this;
        }

        public Builder age(Integer age){
            this.age = age;
            return this;
        }

        public User build(){
            User user = new User(this);
            // 逻辑校验
            if(user.age < 0){
                throw new IllegalArgumentException("");
            }
            return user;
        }
    }

}
